package corej.course.gui;

import java.util.EventObject;
import java.util.EventListener;

/**
 * Desc:
 * Author: sunjs
 * Date: 2009-11-17 11:23:27
 */
public class TestEvent {

    public static void main(String[] args) {
        Girl g = new Girl("芙蓉姐姐");
        EmotionListener b = new Boy("刘春阳");
        g.addEmotionListener(b);
        g.fire();
        System.out.println("");
        g.removeEmotionListener(b);
    }

    /*
    * 事件对象中会封装事件源对象
    */
    static class EmotionEvent extends EventObject {
        public EmotionEvent(Object source) {
            super(source);
        }
    }

    /*
    * 监听接口中的每一个方法，都应该以对应的事件对象作为参数
    */
    static interface EmotionListener extends EventListener {
        void whatCanIDoWhenGirlHappy(EmotionEvent e);

        void whatCanIdoWhenGirlSad(EmotionEvent e);
    }

    static class Boy implements EmotionListener {
        String name;

        public Boy(String name) {
            this.name = name;
        }

        public void whatCanIDoWhenGirlHappy(EmotionEvent e) {
            Object o = e.getSource();
            Girl g = (Girl) o;
            String girlName = g.getName();
            System.out.println(name + " said: " + girlName + ", 你爽我也爽,大家爽才是真的爽");
        }

        public void whatCanIdoWhenGirlSad(EmotionEvent e) {
            Object o = e.getSource();
            Girl g = (Girl) o;
            String girlName = g.getName();
            System.out.println(name + " said: " + girlName + ", 你不爽我也很不爽");
        }

    }

    static class Girl {
        String name;
        EmotionListener bf;

        public Girl(String name) {
            this.name = name;
        }

        public String getName() {
            return name;
        }

        // 建立授权关系
        public void addEmotionListener(EmotionListener bf) {
            this.bf = bf;
            System.out.println(name + " said: 我终于嫁出去了");
        }

        // 解除授权关系
        public void removeEmotionListener(EmotionListener bf) {
            if (this.bf == bf) {
                System.out.println(name + " said: 离开你，我可怎么活呢？");
                this.bf = null;
            }
        }

        public void fire() {
            EmotionEvent e = new EmotionEvent(this);
            for (int day = 1; day <= 10; day++) {
                //所谓的事件源给事件监听器，发送事件对象 就是事件源用事件对象为参数，调用事件监听器的相应方法
                System.out.println("Day " + day);
                if (day % 2 == 1)
                    bf.whatCanIdoWhenGirlSad(e);
                else
                    bf.whatCanIDoWhenGirlHappy(e);
            }
        }
    }
}